import csv
import time

import pandas as pd
import requests


def parse_cookie_string(cookie_string):
    cookies = {}
    for item in cookie_string.split('; '):
        if '=' in item:
            key, value = item.split('=', 1)
            cookies[key] = value
    return cookies


# 发送携带 Cookie 的 GET 请求
def send_get_request_with_cookies(url, cookies):
    try:
        response = requests.get(url, cookies=cookies)
        # 检查响应状态码
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"Request error occurred: {req_err}")
    return None


def send_post_request_with_cookies_and_params(url, cookies, data):
    try:
        response = requests.post(url, data=data, cookies=cookies, timeout=10)
        # 检查响应状态码
        response.raise_for_status()
        # 尝试将响应内容转为 JSON 格式
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.JSONDecodeError:
        print("响应内容不是有效的 JSON 格式。")
    except requests.exceptions.RequestException as req_err:
        print(f"Request error occurred: {req_err}")
    return None


def BUILDID(lon, lat):
    res = []
    get_url = "https://bdc.ghzrzyw.beijing.gov.cn/eo/bizQuery/visualQuery"
    get_response = send_post_request_with_cookies_and_params(get_url, coo, {
        'lon': lon,
        'lat': lat
    })
    if get_response:
        for data in get_response['data']:
            res.append([data.get('BUILDID'), data.get('LDZL')])
    return res


def dyid(buildid):
    res = []
    get_url = "https://bdc.ghzrzyw.beijing.gov.cn/eo/bizQuery/getLjzInfo"
    get_response = send_post_request_with_cookies_and_params(get_url, coo, {
        'buildid': buildid
    })
    if get_response:
        if get_response.get('data'):
            for data in get_response.get('data'):
                res.append([data.get('dyid'), data.get('ldzl')])
        else:
            print(buildid, "为空")
    return res


def mianji(ljzdyid):
    res = []
    get_url = "https://bdc.ghzrzyw.beijing.gov.cn/eo/platform/doubleResultSet"
    get_response = send_post_request_with_cookies_and_params(get_url, coo, {
        'sourceId': '162120',
        'rowsId': '162121',
        'ljzdyid': ljzdyid
    })
    if get_response:
        if get_response.get('data'):
            for data in get_response.get('data'):
                res.append(
                    [data.get('SHBW'), data.get('FWYT1'), data.get('SCJZMJ'), data.get('DYH'),
                     data.get('GHYT'), data.get('QSC'), data.get('ZZC')])
        else:
            print(ljzdyid, '为空')
    return res


def invoke(lon, lat, cell_id):
    print(cell_id)
    res = []
    buildids = BUILDID(lon, lat)
    for buildid in buildids:
        if buildid[0]:
            dyids = dyid(buildid[0])
            for id in dyids:
                mianjis = mianji(id)
                mianjis = [t + [cell_id, id[1], buildid[1]] for t in mianjis]
                res.extend(mianjis)
                print(id[1])
                time.sleep(3)
        else:
            print('buildid为空')
    return res


if __name__ == "__main__":
    coo = 'LOGID=5d8c0b96-462a-4295-9f68-3a07750405dc; JSESSIONID=5F0384987748A478C4959F85CA382EB5; TOKEN_COOKIE_KEY=fbaa82ea-895c-448d-a44e-8dc9e56bde8a; LOGID=5d8c0b96-462a-4295-9f68-3a07750405dc; openstack_cookie_insert=58976419; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22196cc94f87a1304-025ab934fa659f-4c657b58-2073600-196cc94f87b2060%22%7D; _va_id=f5d60e94daac12a2.1747189037.2.1747271189.1747271189.; _va_ses=*'
    coo = parse_cookie_string(coo)
    df = pd.read_csv(r"D:\fttr\通州wgs经纬度.csv")
    with open('/fttr/通州面积.csv', 'a', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        for row in df.itertuples():
            writer.writerows(invoke(row.wgs84经度, row.wgs84纬度, row.中文名称))  # 写入所有行
